import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'

// 创建axios实例
const service: AxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // 在请求发送之前做一些处理
        const token = localStorage.getItem('token')
        if (token && config.headers) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    (error: any) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse<any>) => {
        return response.data
    },
    (error: any) => {
        return Promise.reject(error)
    }
)

interface RequestConfig extends InternalAxiosRequestConfig {
    params?: any
    data?: any
}

const request = {
    get<T = any>(url: string, params?: object, config?: RequestConfig): Promise<T> {
        return service.get(url, { params, ...config })
    },
    post<T = any>(url: string, data?: object, config?: RequestConfig): Promise<T> {
        return service.post(url, data, config)
    },
    put<T = any>(url: string, data?: object, config?: RequestConfig): Promise<T> {
        return service.put(url, data, config)
    },
    delete<T = any>(url: string, data?: object, config?: RequestConfig): Promise<T> {
        return service.delete(url, { data, ...config })
    }
}

export default request
